//
//  ChooseSignViewController.m
//  yigou
//
//  Created by 秦乾龙 on 17/1/13.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "ChooseSignViewController.h"
#import "ZYTagSignView.h"
#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"
#import "ChooseTribeViewController.h"
@interface ChooseSignViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,retain) UITableView *mainTableView;
@property (nonatomic,retain) NSMutableDictionary *tagDic;
@property (nonatomic,retain) NSMutableArray *tagArr;
@property (nonatomic,retain) NSMutableArray *tagSelectArr;
@property (nonatomic,retain) NSString *bannerImgUrl;
@property (assign, nonatomic) BOOL pageToEnd;
@property (assign, nonatomic) NSInteger page;
@property (assign, nonatomic) NSInteger limit;
@end

@implementation ChooseSignViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //隐藏系统导航
    self.navigationController.navigationBarHidden = YES;
    self.limit = 10;
    
    
    [self setUI];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _tagDic = [NSMutableDictionary new];
    _tagSelectArr = [NSMutableArray array];
    _tagArr = [NSMutableArray array];
    //数据请求
    [self request];
}
- (void)setUI
{
    self.view.backgroundColor = [UIColor colorWithRed:32/255.0 green:32/255.0 blue:32/255.0 alpha:1.0f];
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, -21,ScreenW , ScreenH+21-130*kScale) style:UITableViewStyleGrouped];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    [self.view addSubview:_mainTableView];
    //[self addRefreshHeader:_mainTableView];
    [self addLoadMoreFooter:_mainTableView];
    CGFloat nextBtnH = 130*kScale;
    ZYButton *nextBtn = [ZYButton buttonWithType:UIButtonTypeCustom];
    nextBtn.frame = CGRectMake(0, ScreenH-nextBtnH, ScreenW, nextBtnH);
    nextBtn.backgroundColor = [UIColor blackColor];
    [nextBtn setTitle:@"OK,下一步" forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(nextClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextBtn];
}
////下拉刷新
//- (void)refresh {
//    [super refresh];
//    [self request];
//}
//上拉加载
- (void)loadMore {
    if (self.pageToEnd) {
        [ViewFactory showInfoMsg:@"没有下一页了！"];
        [_mainTableView.footer endRefreshing];
        return;
    }
    self.page += 1;
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/sys/index/getIndexTribeLabel?page=%ld&limit=%ld",APIYIGOU,self.page,self.limit];
    DYLog(@".....%ld",self.page);
    request.requestUrl =  url;
    [ViewFactory showLoading];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        NSArray *array = allDic[@"data"][@"list"];
        DYLog(@"66666%@",array);
        if (array.count == 0) {
            [ViewFactory showInfoMsg:@"没有下一页了！"];
            
        }
        else if (array.count<_limit)
        {
            self.pageToEnd = YES;
        }

        DYLog(@".....%ld",array.count);
        [_tagArr addObjectsFromArray: array];
        DYLog(@".....%ld",_tagArr.count);
        [ViewFactory dismissLoading];
        [_mainTableView reloadData];
        [_mainTableView.footer endRefreshing];
    } error:^(YTKBaseRequest *request) {
        [_mainTableView.footer endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [_mainTableView.footer endRefreshing];
    }];
}

- (void)request
{
    self.page = 1;
    self.pageToEnd = NO;
    NSString *urlStr = [NSString stringWithFormat:@"%@/sys/index/getIndexTribeLabel?page=%ld&limit=%ld",APIYIGOU,self.page,self.limit];

//    NSString *urlStr = [NSString stringWithFormat:@"%@/sys/index/getIndexTribeLabel?page=1&limit=10",APIYIGOU];
    
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = urlStr;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        NSLog(@"1111111%@",allDic);
        _tagArr = allDic[@"data"][@"list"];
        [_mainTableView reloadData];
    } error:^(YTKBaseRequest *request) {
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
    NSString *urlStr2 = [NSString stringWithFormat:@"%@/sys/index/indexImg?type=01-1",APIYIGOU]
    ;
    
    DYBaseRequest *request2 = [DYBaseRequest new];
    request2.requestUrl = urlStr2;
    [request2 dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        NSLog(@"2222222%@",allDic);
        NSArray *dataArr = allDic[@"data"];
        if (dataArr.count>0) {
            _bannerImgUrl = allDic[@"data"][0][@"ad_img_url"];
        }
        [_mainTableView reloadData];
    } error:^(YTKBaseRequest *request) {
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    if (section==0) {
//        return 1;
//    }
    return 1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell =[[NSBundle mainBundle ]loadNibNamed:@"ZYTableViewCell" owner:nil options:nil][0];
    }
    //设置cell不能点击
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section==0)
    {
        UIImageView *bannerImg = [[UIImageView alloc]init];
        bannerImg.frame = CGRectMake(0, 0, ScreenW, 418*kScale);
        NSString *imgurl = [NSString stringWithFormat:@"%@?imageView2/0/w/%d/h/%d", _bannerImgUrl, (int)ScreenW, 0];
        [bannerImg sd_setImageWithURL:[NSURL URLWithString:imgurl]];;
        [cell addSubview:bannerImg];
    }
    else if (indexPath.section==1)
    {
        
        for (int i = 0; i < _tagArr.count;i++)
        {
            
            CGFloat leftSpace = 30*kScale;
            CGFloat line = i/3;
            CGFloat colum = i%3;
            CGFloat tagSignW = 164*kScale;
            CGFloat tagSignH = 164*kScale+72*kScale;
            CGFloat addImgH = 41*kScale;
            CGFloat publicSpaceW = (ScreenW-2*leftSpace-3*tagSignW)/2;
            CGFloat publicSpaceH = 30*kScale;
            
            ZYTagSignView * tagSign = [[ZYTagSignView alloc]initWithBackgroundImg:_tagArr[i][@"bg_img"]];
            tagSign.frame = CGRectMake(30*kScale+(tagSignW+publicSpaceW)*colum, 50*kScale+(tagSignH+publicSpaceH)*line, tagSignW, tagSignH);
            tagSign.addBtn.addImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"add"]];
            tagSign.addBtn.tag = i+10;
            tagSign.addBtn.selected = NO;
            tagSign.addBtn.titleLabel.font = [UIFont systemFontOfSize:15];
            tagSign.addBtn.tagTitle = _tagArr[i][@"tribe_label"];
            tagSign.addBtn.addImg.frame = CGRectMake((tagSignW-addImgH)/2, (tagSignW-addImgH)/2, addImgH, addImgH);
            [tagSign.addBtn addSubview:tagSign.addBtn.addImg];
            [tagSign.addBtn addTarget:self action:@selector(addBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            tagSign.titleLable.text = _tagArr[i][@"tribe_label"];
            tagSign.titleLable.textAlignment = NSTextAlignmentCenter;
            tagSign.titleLable.adjustsFontSizeToFitWidth = YES;

//            tagSign.backgroundColor = [UIColor redColor];
            [cell addSubview:tagSign];
        }
        
    }
    return cell;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSelector:@selector(cancleSelect) withObject:nil afterDelay:0.1f];
   
    
}
- (void)cancleSelect
{
    [_mainTableView deselectRowAtIndexPath:[_mainTableView indexPathForSelectedRow] animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 418*kScale;
    }
    return  (50+266*(_tagArr.count+2)/3)*kScale;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
//修改状态栏字体
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
//点击加号按钮
- (void)addBtnClick:(ZYButton*)sender
{
    if (sender.selected==NO) {
        sender.addImg.image = [UIImage imageNamed:@"选择"];
        sender.selected=YES;
        [_tagDic setObject:sender.tagTitle forKey:[NSString stringWithFormat:@"%ld",sender.tag]];
        NSLog(@"111111%@",_tagDic);
    }
    else
    {
        sender.addImg.image = [UIImage imageNamed:@"add"];
        sender.selected=NO;
        [_tagDic removeObjectForKey:[NSString stringWithFormat:@"%ld",sender.tag]];
        NSLog(@"22222%@",_tagDic);
    }

}
//点击下一步
- (void)nextClick
{
    
    [_tagSelectArr addObjectsFromArray:_tagDic.allValues];
    if (_tagSelectArr.count<3)
    {
        [ViewFactory showInfoMsg:@"请选择至少3个标签"];
        [_tagSelectArr removeAllObjects];
    }
    else
    {
        ChooseTribeViewController *chooseTribe = [[ChooseTribeViewController alloc]init];
        chooseTribe.tagSelectArr = _tagSelectArr;
        [self.navigationController pushViewController:chooseTribe animated:YES];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
